package com.freedom.clue.service.impl;

import com.freedom.auth.vo.ClueExportVo;
import com.freedom.clue.mapper.ClueMapper;
import org.springframework.beans.BeanUtils;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.freedom.auth.vo.ClueImportVo;
import com.freedom.clue.domain.Clue;
import com.freedom.clue.service.IClueService;
import com.freedom.base.service.impl.BaseServiceImpl;
import com.freedom.clue.verifyHandler.ClueVerifyHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author freedom
 * @since 2023-10-18
 */
@Service
public class ClueServiceImpl extends BaseServiceImpl<Clue> implements IClueService {
    @Autowired
    private ClueVerifyHandler clueVerifyHandler;

    @Autowired
    private ClueMapper clueMapper;

    @Override
    public Clue getByName ( String name ) {
        return clueMapper.getByName(name);
    }


    /**
     * excel导入
     *
     * @param file
     * @return
     * @throws Exception
     */
    @Override
    public String importExcel ( MultipartFile file ) throws Exception {
        ImportParams importParams = new ImportParams();
        //表格标题行数,默认0
        importParams.setTitleRows(0);
        //是否需要校验上传的Excel
        importParams.setNeedVerify(true);
        //告诉easypoi我们自定义的验证器
        importParams.setVerifyHandler(clueVerifyHandler);
        ExcelImportResult<ClueImportVo> result = ExcelImportUtil.importExcelMore(file.getInputStream(), ClueImportVo.class, importParams);
        if (!result.isVerifyFail() && !CollectionUtils.isEmpty(result.getList())) {
            for (ClueImportVo vo : result.getList()) {
                Clue clue = new Clue();
                BeanUtils.copyProperties(vo, clue);
                this.insert(clue);
            }
        } else {
            for (ClueImportVo vo : result.getFailList()) {
                System.out.println(("校验失败的详细为 ：{}" + vo));
            }
            return "文档校验失败";
        }
        return "导入成功";
    }

    /**
     * excel导出
     *
     * @return
     */
    @Override
    public List<ClueExportVo> getClueExportList () {
        List<Clue> clues = clueMapper.getAll();
        // clues转成export集合
        return clues.stream().map(clue -> {
            ClueExportVo vo = new ClueExportVo();
            BeanUtils.copyProperties(clue, vo);
            return vo;
        }).collect(Collectors.toList());
    }


}
